import express from 'express';
import makeres from '../utils/res';
import TokenTools from '../service/tools/token';
import { notCheckTokenApis } from '../server.config';
import 'express-async-errors';

const app = express();

// 请求拦截 - token验证
const notCheck = Object.values(notCheckTokenApis);
app.use(async ({ originalUrl: api, headers }, res, next) => {
	const token = headers['pakchoi-token'];
	const deCheck = notCheck.some((url) => api.includes(url));
	if (deCheck) return next();
	const { u_id, level } = await TokenTools.check(token);
	res.locals = { u_id, level };
	next();
});

//路由
app.use('/user', require('./user'));
app.use('/usermanager', require('./usermanager'));
app.use('/auth', require('./auth'));
app.use('/mjconf', require('./mjconf'));
app.use('/global', require('./global'));
app.use('/super', require('./super'));

// 全局异常处理
app.use((err, req, res, next) => {
	if (err) {
		let { message, name } = err;
		console.log({ name, message });
		switch (name) {
			case 'AuthError':
				return res.send(makeres.validateFailed(message));
			case 'TargetDataNoneError':
				return res.send(makeres.error('目标数据不存在！'));
			case 'ParameterError':
				return res.send(makeres.error('参数异常！'));
			default:
				if (message.includes('foreign key constraint fails')) message = 'foreign key constraint fails！';
				return res.send(makeres.error(message));
		}
	}
});
export default app;
